import Request from './luch-request/luch-request/index.js' // 下载的插件
import vm from "@/main.js"
import config from './config.js'
let url = "/api"
//#ifdef MP-WEIXIN 
url = config.baseUrl;
//#endif
let http = new Request({
	baseURL: url,
	method: 'POST',
	custom: {
		loadingText: "请求中",
		isShowErrTip: true
	},
	dataType: 'json',
	timeout: 60000,
});
http.interceptors.request.use((req) => {
	if (!vm.$validatenull(req.custom.loadingText)) {
		vm.$showLoading(req.custom.loadingText)
	}
	console.log("reqData", req.data);
	return req;
}, req => {
	return Promise.reject(req);
})


http.interceptors.response.use((response) => {
	let loadingText = response.config.custom.loadingText;
	if (!vm.$validatenull(loadingText)) {
		uni.hideLoading();
	}
	
	let data = response.data;
	console.log("response", response);
	if (data.resultCode == "0000") {
		return [null, data.data];
	} else {
		if (response.config.custom.isShowErrTip) {
			let methodCode = response.config.header.methodCode;
			if(methodCode == "2000" || methodCode == "2001" || methodCode == "2002" || methodCode == "2003") {
				uni.$emit("isShowLoading",false);
			}
			vm.$showModal(data.resultMsg);
		}
		//业务逻辑错误
		return [data.resultCode, null];
	}
}, (response) => { /*  对响应错误做点什么 （statusCode !== 200）*/ //请求错误
	console.log("response", response)
	uni.hideLoading();
	vm.$showModal("请求错误,请稍后再试");
	return Promise.reject(["error", null]);
})

let requestUtil = (methodCode,params,loadingText = "请求中")=>{
	return http.request({
		data:{
			...params,
			methodCode
		},
		header:{
			methodCode,
			'content-type': 'application/json',
			'requestTime': new Date().getTime(),
			'requestId': new Date().getTime(),
			'appId': "wx1863a38d48727f02"
		},
		custom: {
			loadingText
		},
	})
}

module.exports = requestUtil;
